from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.decorators import action
from rest_framework_simplejwt.authentication import JWTAuthentication

from apps.databasetest.models import DatabaseConfig
from apps.datavalidation.databaseconfigeditserializer import DatabaseConfigEditSerializer
from utils.jsonResponse import SuccessResponse, ErrorResponse,DetailResponse

# 导入服务层
from apps.datavalidation.services.dbconfig import DBconfigService  # 替换为实际路径
from apps.datavalidation.services.sqlserver.validation import ValidationService


class DatabaseConfigApiViewSet(ViewSet):
    """
    数据库配置查询API视图
    直接调用ValSqlServerService中的方法处理业务逻辑
    """

    # permission_classes = ()  # 允许匿名访问
    # authentication_classes = ()  # 清空认证类，不进行任何认证校验
    permission_classes = [IsAuthenticated]  # 权限控制（根据需求调整）
    authentication_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_summary="查询所有数据库配置",
        operation_description="调用ValSqlServerService获取所有DatabaseConfig数据",
        responses={
            200: "查询成功，返回配置列表",
            500: "查询失败（含错误信息）"
        }
    )
    def list(self, request):
        """查询所有数据库配置（调用服务层get_all_database_configs方法）"""
        try:
            # 直接调用服务层方法
            result = DBconfigService.get_all_database_configs()
            return Response({
                "success": True,
                "data": result,
                "total": len(result)
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({
                "success": False,
                "error": str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @swagger_auto_schema(
        operation_summary="按机构ID查询配置",
        operation_description="调用服务层按organ_id筛选数据库配置",
        manual_parameters=[
            openapi.Parameter(
                name="organ_id",
                in_=openapi.IN_QUERY,
                description="所属机构ID",
                type=openapi.TYPE_STRING,
                required=True,
                example="HOSPITAL_001"
            )
        ],
        responses={
            200: "查询成功",
            400: "参数缺失",
            500: "查询失败"
        }
    )
    # 通过入参的方式查询，但是此处不用，该接口暂时作废
    @action(detail=False, methods=['get'], url_path='filter-by-organ')
    def filter_by_organ(self, request):
        """按机构ID查询（调用服务层get_database_configs_by_organ方法）"""
        # 获取请求参数
        organ_id = request.query_params.get("organ_id")
        if not organ_id:
            return Response({
                "success": False,
                "error": "缺少参数organ_id"
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 调用服务层带参数的方法
            result = DBconfigService.get_database_configs_by_organ(organ_id)
            testres = ValidationService.val_real_time(organ_id)
            return Response({
                "success": True,
                "organ_id": organ_id,
                "data": result,
                "total": len(result)
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({
                "success": False,
                "error": f"查询失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['get'], url_path='filter_by_token')
    def filter_by_token(self, request):
        """按当前用户所属机构ID查询,无入参，机构id自动查询（调用服务层get_database_configs_by_token方法）"""
        # 先获取当前登录用户
        print(request.query_params)
        query_params = request.query_params
        current_user = request.user
        # 只有当上文中permission_classes和authentication_classes设置了才会进行验证，否则就会是匿名用户
        if not current_user.is_authenticated:
            return Response({
                "success": False,
                "error": "当前登录未登录"
            }, status=status.HTTP_400_BAD_REQUEST)
        organ_id = getattr(request.user, 'dept_id', '')
        if not organ_id:
            return Response({
                "success": False,
                "error": "当前登录用户不属于任何机构/部门"
            }, status=status.HTTP_400_BAD_REQUEST)
        try:
            # 判断当前登录用户是否为superadmin超级管理员，如果是的话则返回所有数据。
            if current_user.id != '456b688c-8ad5-46de-bc2e-d41d8047bd42':
                result = DBconfigService.get_database_configs_by_token(organ_id,query_params)
            else:
                # 调用服务层带参数的方法
                result = DBconfigService.get_all_database_configs(query_params)
            # 校验语句，此处暂时不用
            testres = ValidationService.val_real_time(organ_id)
            # return Response({
            #     "success": True,
            #     "organ_id": organ_id,
            #     "data": result,
            #     "total": len(result)
            # }, status=status.HTTP_200_OK)
            return SuccessResponse(msg='获取成功', data=result, total=len(result))
        except Exception as e:
            return Response({
                "success": False,
                "error": f"查询失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['get'], url_path='get_detail')
    def get_detail(self, request):
        """获取数据库配置详情（支持按ID查询）"""
        # 获取查询参数中的ID
        config_id = request.query_params.get('id', '')
        if not config_id:
            return Response({
                "success": False,
                "error": "请提供配置ID"
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证用户登录状态
        current_user = request.user
        if not current_user.is_authenticated:
            return Response({
                "success": False,
                "error": "当前用户未登录"
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 超级管理员可以查看所有详情，普通用户只能查看本机构详情
            if current_user.id == '456b688c-8ad5-46de-bc2e-d41d8047bd42':
                # 超级管理员：无机构限制
                result = DBconfigService.get_database_config_detail(config_id)
            else:
                # 普通用户：只能查看本机构数据
                organ_id = getattr(request.user, 'dept_id', '')
                if not organ_id:
                    return Response({
                        "success": False,
                        "error": "当前用户不属于任何机构/部门"
                    }, status=status.HTTP_400_BAD_REQUEST)
                result = DBconfigService.get_database_config_detail(config_id, organ_id)

            if not result:
                return Response({
                    "success": False,
                    "error": "未找到对应配置"
                }, status=status.HTTP_404_NOT_FOUND)

            return SuccessResponse(msg='获取详情成功', data=result)
        except Exception as e:
            return Response({
                "success": False,
                "error": f"查询详情失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 获取编辑数据（用于表单回显）
    @action(detail=False, methods=['get'], url_path='get_edit_data')
    def get_edit_data(self, request):
        """获取编辑所需的配置数据（带权限控制）"""
        config_id = request.query_params.get('id', '')
        if not config_id:
            return Response({
                "success": False,
                "error": "请提供配置ID"
            }, status=status.HTTP_400_BAD_REQUEST)

        current_user = request.user
        if not current_user.is_authenticated:
            return Response({
                "success": False,
                "error": "当前用户未登录"
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 权限控制：超级管理员无限制，普通用户只能编辑本机构数据
            if current_user.id == '456b688c-8ad5-46de-bc2e-d41d8047bd42':
                result = DBconfigService.get_database_config_edit_data(config_id)
            else:
                organ_id = getattr(request.user, 'dept_id', '')
                if not organ_id:
                    return Response({
                        "success": False,
                        "error": "当前用户不属于任何机构/部门"
                    }, status=status.HTTP_400_BAD_REQUEST)
                result = DBconfigService.get_database_config_edit_data(config_id, organ_id)

            if not result:
                return Response({
                    "success": False,
                    "error": "未找到对应配置"
                }, status=status.HTTP_404_NOT_FOUND)

            return SuccessResponse(msg='获取编辑数据成功', data=result)
        except Exception as e:
            return Response({
                "success": False,
                "error": f"获取编辑数据失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 提交编辑内容
    @action(detail=False, methods=['put'], url_path='submit_edit')
    def submit_edit(self, request, pk):
        """提交编辑后的配置数据"""
        config_id = pk
        if not config_id:
            return Response({
                "success": False,
                "error": "请提供配置ID"
            }, status=status.HTTP_400_BAD_REQUEST)

        current_user = request.user
        if not current_user.is_authenticated:
            return Response({
                "success": False,
                "error": "当前用户未登录"
            }, status=status.HTTP_400_BAD_REQUEST)

        # 关键步骤1：查询要编辑的实例（必须存在）
        try:
            instance = DatabaseConfig.objects.get(id=config_id)
        except DatabaseConfig.DoesNotExist:
            return Response({
                "success": False,
                "error": "要编辑的配置不存在"
            }, status=status.HTTP_404_NOT_FOUND)

        # 关键步骤2：序列化器传入instance，明确是更新操作
        serializer = DatabaseConfigEditSerializer(
            instance=instance,  # 关联实例
            data=request.data
        )
        if not serializer.is_valid():
            return Response({
                "success": False,
                "error": serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 权限控制（保持不变）
            if current_user.id == '456b688c-8ad5-46de-bc2e-d41d8047bd42':
                result = DBconfigService.update_database_config(
                    config_id,
                    serializer.validated_data,
                    modifier=current_user.username
                )
            else:
                organ_id = getattr(request.user, 'dept_id', '')
                if not organ_id:
                    return Response({
                        "success": False,
                        "error": "当前用户不属于任何机构/部门"
                    }, status=status.HTTP_400_BAD_REQUEST)
                result = DBconfigService.update_database_config(
                    config_id,
                    serializer.validated_data,
                    organ_id=organ_id,
                    modifier=current_user.username
                )

            if not result:
                return Response({
                    "success": False,
                    "error": "编辑失败，未找到对应配置或无权限"
                }, status=status.HTTP_404_NOT_FOUND)

            return SuccessResponse(msg='编辑成功', data=result)
        except Exception as e:
            return Response({
                "success": False,
                "error": f"编辑失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['post'], url_path='add_config')
    def add_config(self, request):
        """新增数据库配置"""
        current_user = request.user
        if not current_user.is_authenticated:
            return Response({
                "success": False,
                "error": "当前用户未登录"
            }, status=status.HTTP_400_BAD_REQUEST)

        # 数据验证（复用编辑的序列化器，字段一致）
        serializer = DatabaseConfigEditSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({
                "success": False,
                "error": serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 超级管理员可以指定机构，普通用户只能关联自己的机构
            if current_user.id == '456b688c-8ad5-46de-bc2e-d41d8047bd42':
                # 超级管理员：允许指定organ_id
                organ_id = request.data.get('organ_id', '')
                if not organ_id:
                    return Response({
                        "success": False,
                        "error": "超级管理员新增需指定机构ID"
                    }, status=status.HTTP_400_BAD_REQUEST)
            else:
                # 普通用户：只能关联自己的机构
                organ_id = getattr(request.user, 'dept_id', '')
                if not organ_id:
                    return Response({
                        "success": False,
                        "error": "当前用户不属于任何机构/部门，无法新增"
                    }, status=status.HTTP_400_BAD_REQUEST)

            # 调用服务层新增方法
            result = DBconfigService.create_database_config(
                data=serializer.validated_data,
                organ_id=organ_id,
                creator=current_user.username  # 记录创建人
            )

            return SuccessResponse(msg='新增成功', data=result)
        except Exception as e:
            return Response({
                "success": False,
                "error": f"新增失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['delete'], url_path='delete_config')
    def delete_config(self, request):
        """删除数据库配置"""
        config_id = request.query_params.get('id', '')
        if not config_id:
            return Response({
                "success": False,
                "error": "请提供配置ID"
            }, status=status.HTTP_400_BAD_REQUEST)

        current_user = request.user
        if not current_user.is_authenticated:
            return Response({
                "success": False,
                "error": "当前用户未登录"
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 权限控制：超级管理员可删除所有，普通用户只能删除本机构
            if current_user.id == '456b688c-8ad5-46de-bc2e-d41d8047bd42':
                # 超级管理员：直接删除
                result = DBconfigService.delete_database_config(config_id)
            else:
                # 普通用户：验证机构权限
                organ_id = getattr(request.user, 'dept_id', '')
                if not organ_id:
                    return Response({
                        "success": False,
                        "error": "当前用户不属于任何机构/部门"
                    }, status=status.HTTP_400_BAD_REQUEST)
                result = DBconfigService.delete_database_config(config_id, organ_id)

            if not result:
                return Response({
                    "success": False,
                    "error": "删除失败，未找到对应配置或无权限"
                }, status=status.HTTP_404_NOT_FOUND)

            return SuccessResponse(msg='删除成功')
        except Exception as e:
            return Response({
                "success": False,
                "error": f"删除失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)